package com.xc.service.baseService.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.entity.base.BaseEntity;
import com.xc.exception.BusinessException;
import com.xc.service.baseService.BaseService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> implements BaseService<T> {

    @Autowired
    private ThreadLocalService threadLocal;

    private Collection<T> entityPre(Collection<T> list, Boolean isAdd) {
        if (list.size() == 0 || list == null) {
            throw new BusinessException(9999, "entity或者ids为空");
        }
        LocalDateTime date = LocalDateTime.now();
        Iterator<T> iterator = list.iterator();
        while (iterator.hasNext()) {
            T next = iterator.next();
            if (isAdd) {
                next.setCreateTime(date);
            }
            next.setUpdateTime(date);
            if (threadLocal != null && StrUtil.isNotBlank(threadLocal.getThreadLocal())) {
                if (isAdd) {
                    next.setCreateUser(threadLocal.getThreadLocal());
                }
                next.setUpdateUser(threadLocal.getThreadLocal());
            }
        }
        return list;
    }

    @Override
    public Boolean savePre(T entity) {
        List<T> entityList = entityPre(Collections.singletonList(entity), true).stream().toList();
        return save(entityList.get(0));
    }

    @Override
    public Boolean saveBatchPre(Collection<T> entityList) {
        entityList = entityPre(entityList, true);
        return saveBatch(entityList);
    }

    @Override
    public Boolean updateByIdPre(T entity) {
        List<T> entityList = entityPre(Collections.singletonList(entity), false).stream().toList();
        return updateById(entityList.get(0));
    }

    @Override
    public Boolean updateBatchByIdPre(Collection<T> entityList) {
        entityList = entityPre(entityList, false);
        return updateBatchById(entityList);
    }
}
